package nju.software.xkxt.data.dao.implement;

import java.util.List;

import nju.software.xkxt.data.dao.CourseDao;
import nju.software.xkxt.data.dataobject.CourseDO;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * @author typ
 * 
 */
@SuppressWarnings("unchecked")
public class CourseDaoImpl extends HibernateDaoSupport implements CourseDao {

	@Override
	public CourseDO getCourseById(int c_id) {
		String hql = "from CourseDO where CId=?";
		List<CourseDO> courseDOs = getHibernateTemplate().find(hql, c_id);
		return courseDOs.size() != 0 ? courseDOs.get(0) : null;
	}

	@Override
	public List<CourseDO> getCourse() {
		String hql = "from CourseDO";
		List<CourseDO> courseDOs = getHibernateTemplate().find(hql);
		return courseDOs;
	}

	@Override
	public boolean addCourse(CourseDO courseDO) {
		boolean isAdd = false;
		if(courseDO!=null){
			try {
				this.getHibernateTemplate().save(courseDO);
				isAdd = true;
			} catch (Exception e) {
				isAdd = false;
			}		
		}else {
			isAdd = false;
		}
		return isAdd;
	}

	@Override
	public boolean updateCourse(CourseDO courseDO) {
		boolean isUpdate = false;
		if(courseDO!=null){
			try {
				this.getHibernateTemplate().update(courseDO);
				isUpdate = true;
			} catch (Exception e) {
				isUpdate = false;
			}
		}else {
			isUpdate = false;
		}
		return isUpdate;
	}

	@Override
	public boolean deleteCourse(int cid) {
		String sql = "delete from CourseDO where  =:cid";
		boolean b;
		Session session = this.getSession();
		try {

			Query query = session.createQuery(sql);
			query.setParameter("cid", cid);
			query.executeUpdate();
			b = true;
		} catch (Exception e) {
			b = false;
		}
		session.close();
		return b;
	}

	@Override
	public int getMaxID() {
		String hql = "select max(CId) from CourseDO";
		Session session = this.getSession();
		Query query = session.createQuery(hql);
		int maxID;
		if (query.uniqueResult() != null) {
			maxID = (Integer) query.uniqueResult();
		} else {
			maxID = 0;
		}
		session.close();
		return maxID;
	}

	@Override
	public List<CourseDO> gerCourseByTid(int t_id) {
		String hql = "from CourseDO where TId=?";
		List<CourseDO> courseDOs = getHibernateTemplate().find(hql, t_id);
		return courseDOs;
	}

}
